package gamecfg

import (
	"encoding/json"
	"fmt"
	"github.com/gogf/gf/v2/os/gctx"
	"github.com/gogf/gf/v2/os/glog"
	"sort"
	"xr-game-server/core/constants/common"
	"xr-game-server/core/xrjson"
)

var itemSourceMap = make(map[uint64]*ItemSourceCfg)
var IdArray = make([]*ItemSourceCfg, common.Zero)

func initItemSource() {
	xrjson.RegLoadJsonHandler("itemSource.json", loadItemSource)
}

type ById []*ItemSourceCfg

func (a ById) Len() int {
	return len(a)
}
func (a ById) Less(i, j int) bool {
	return a[i].Id < a[j].Id
}
func (a ById) Swap(i, j int) {
	a[i], a[j] = a[j], a[i]
}

// ItemSourceCfg 物品来源表
type ItemSourceCfg struct {
	Id   uint64 `json:"id"`
	Name string `json:"name"`
}

func loadItemSource(jsonData string) {
	err := json.Unmarshal([]byte(jsonData), &itemSourceMap)
	if err != nil {
		panic(fmt.Errorf("%v 文件加载错误 %v", jsonData, err))
	}
	for _, item := range itemSourceMap {
		IdArray = append(IdArray, item)
	}
	sort.Sort(ById(IdArray))
	glog.Warningf(gctx.New(), "%s数据加载成功,长度:%v", jsonData, len(itemSourceMap))
}

func GetItemSources() []*ItemSourceCfg {
	return IdArray
}

func GetItemSourceById(itemSourceId uint64) *ItemSourceCfg {
	item, ok := itemSourceMap[itemSourceId]
	if !ok {
		return nil
	}
	return item
}
